package com.sqlweb.sqlweb.base;

import lombok.extern.slf4j.Slf4j;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.RList;
import org.rosuda.REngine.Rserve.RConnection;

import java.util.Arrays;

@Slf4j
public class CatService {
    private static final String RSERVE_HOST = "localhost";
    private static final int RSERVE_PORT = 6311;

    public void executeService(double currentTheta, int[] respData, String itemParPath, int maxNI, double maxSE) {
        try {
            RConnection connection = new RConnection(RSERVE_HOST, RSERVE_PORT);
            connection.eval("source('E:/CAT/fun_ayuan_test_finish.R')");

            // 传递参数
            connection.assign("currentTheta", new double[]{currentTheta});
            connection.assign("respData", respData);
            connection.assign("itemParPath", itemParPath);
            connection.assign("maxNI", new double[]{maxNI});
            connection.assign("maxSE", new double[]{maxSE});

            log.info("Parameter currentTheta: " + currentTheta);
            log.info("Parameter respData: " + Arrays.toString(respData));
            log.info("Parameter itemParPath: " + itemParPath);

            // 执行 R 命令
            String rCommand = "try(selectQuestion(currentTheta, respData, itemParPath, maxNI, maxSE), silent=TRUE)";
            log.info("Executing R command: " + rCommand);
            REXP result = connection.eval(rCommand);

            // 检查结果
            if (result.inherits("try-error")) {
                log.error("R Serve Eval Exception: " + result.asString());
            } else if (result.isString()) {
                String[] returnedStrings = result.asStrings();
                log.info("R returned strings: " + Arrays.toString(returnedStrings));
            } else if (result.isNumeric()) {
                double[] returnedNumbers = result.asDoubles();
                log.info("R returned numeric values: " + Arrays.toString(returnedNumbers));
            } else if (result.isList()) {
                RList returnedList = result.asList();
                log.info("R returned a list with size: " + returnedList.size());
            } else {
                log.error("Unexpected return type from R.");
            }

            // 关闭连接
            connection.close();
        } catch (Exception e) {
            log.error("An error occurred while communicating with Rserve.", e);
        }
    }
}
